﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Security.Cryptography;

namespace A2.ERP.Common
{
    public static class CommonHelper
    {
        //计算字符串的MD5值
        public static string ComputeStringMD5(string str)
        {
            StringBuilder sbMd5 = new StringBuilder();
            //1.创建MD5对象
            using (MD5 md5 = MD5.Create())
            {

                //把字符串转换为一个byte[]
                byte[] buffer = System.Text.Encoding.Default.GetBytes(str);
                //把byte[]转换为字符串
                //Encoding.UTF8.GetString(buffer)

                //2.计算MD5值
                byte[] mdBytes = md5.ComputeHash(buffer);
                md5.Clear();

                //2.1循环将byte[]中的每个元素以16进制字符串的方式拼接
                for (int i = 0; i < mdBytes.Length; i++)
                {
                    sbMd5.Append(mdBytes[i].ToString("x2"));
                }

                //3.返回
                return sbMd5.ToString();
            }
        }

        //2.计算文件的MD5值
        public static string ComputeFileMD5(string path)
        {
            StringBuilder sbMd5 = new StringBuilder();
            //1.创建Md5对象
            using (MD5 md5 = MD5.Create())
            {
                using (FileStream fsRead = File.OpenRead(path))
                {
                    //2.进行计算
                    byte[] md5Buffer = md5.ComputeHash(fsRead);

                    //3.变量拼接字符串
                    for (int i = 0; i < md5Buffer.Length; i++)
                    {
                        sbMd5.Append(md5Buffer[i].ToString("x2"));
                    }
                }

            }
            return sbMd5.ToString();
        }

    }
}
